<template>
  <div class="allsearch">
    <section class="search-content">
      <el-row :gutter="4" type="flex" justify="start">
        <el-col :span="24">
          <el-cascader
            :change-on-select="true"
            :options="courseCategorys"
            v-model="listQuery.type"
            :props="{value: 'id'}"
            @change="handleFilter"
          />
          <el-select v-model="listQuery.property" style="width:150px;" @change="handleFilter">
            <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="listQuery.keyword"
            style="width:200px"
            placeholder="标题"
            @keyup.enter.native="handleFilter"
          />
          <el-input
            v-model="listQuery.author"
            style="width:200px"
            placeholder="创建者"
            @keyup.enter.native="handleFilter"
          />
          <el-button type="primary" size="medium" @click="handleFilter">搜索</el-button>
          <el-button size="medium" type="info" @click="clearParams">清空</el-button>
        </el-col>
      </el-row>
    </section>
    <!-- 推荐序号设置 -->
    <el-dialog :visible.sync="dialogVisible" title="设置推荐课程" width="980px">
      <el-form ref="sequence" :model="sequence" :rules="rules">
        <el-form-item label="序号" prop="num">
          <el-input v-model="sequence.num" style="width: 280px"/>
          <p style="margin:0">请输入长度不能超过8位的整数</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateCourse">保 存</el-button>
      </div>
    </el-dialog>
    <eltable
      :table-label="tableLabel"
      :table-data="tableData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >
      <el-table-column slot="first" :min-width="10" label="顺序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.recommendedSeq }}</span>
        </template>
      </el-table-column>
      <el-table-column slot="second" :min-width="20" label="课程名称" prop="title" align="center">
        <template slot-scope="scope">
          <el-button type="text">{{ scope.row.title }}</el-button>
        </template>
      </el-table-column>
      <el-table-column slot="isPro" :min-width="10" label="创建者" prop="creator" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleClickDialog(scope)">{{ scope.row.userName }}</el-button>
          <br>
          <span>{{ scope.row.createTimeStr }}</span>
        </template>
      </el-table-column>
      <el-table-column slot="button" :min-width="15" label="操作" prop="manage" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="setRecommend(scope)">设置序号</el-button>
          <el-button type="primary" @click="cancelRecommend(scope)">取消推荐</el-button>
        </template>
      </el-table-column>
    </eltable>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <user-dialog :visiabledialog="userDialog" :dialog-data="dialogData" @changeVisiable="userDialog = false"/>
  </div>
</template>

<script>
import UserDialog from '@/components/Dialog'
import Eltable from '@/components/Eltable'
import Pagination from '@/components/Pagination' // 分页组件
import { getRecommendOpenCourseList, updateOpenCourse } from '@/api/subject/openCourse' // 数据接口
import { getCategoryList } from '@/api/subject/category' // 数据接口
import { getUserDetail } from '@/api/operate/userDetail' // 数据接口
import { getTenantId } from '@/utils/auth'
export default {
  components: {
    Eltable,
    Pagination,
    UserDialog
  },
  data() {
    return {
      userDialog: false,
      dialogData: {},
      dialogVisible: false,
      sequence: {
        entity: {},
        num: ''
      },
      listQuery: {
        type: [],
        property: '',
        keyword: '',
        author: ''
      },
      total: 0,
      currentpage: 1,
      pagesize: 10,
      courseCategorys: [],
      options3: [
        {
          label: '类型',
          value: ''
        },
        {
          label: '直播公开课',
          value: 'liveOpen'
        },
        {
          label: '录播公开课',
          value: 'open'
        }
      ],
      tableLabel: [
        {
          label: '推荐时间', width: '10', prop: 'recommendedTimeStr'
        }
      ],
      tableData: [],
      listFilter: [],
      rules: {
        num: [
          {required: true, message: '必填信息', trigger: 'blur'},
          {min: 1, max: 8, message: '长度不能超过8位', trigger: 'blur'},
          {pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入长度不能超过8位的整数'}
        ]
      }
    }
  },
  mounted() {
    this.getData();
    this.getCategoryList()
  },
  methods: {
    handleClickDialog(scope) {
      getUserDetail(scope.row.userId).then(response => {
        this.dialogData = response.data.item
      });
      this.userDialog = true
    },
    setRecommend(scope) {
      this.dialogVisible = true;
      this.sequence.entity = scope.row
    },
    updateCourse() {
      this.$refs.sequence.validate((valid) => {
        if (valid) {
          this.dialogVisible = false;
          this.sequence.entity.recommended = 1;
          if (!this.sequence.num) this.sequence.num = 100;
          this.sequence.entity.recommendedSeq = this.sequence.num;
          this.sequence.entity.recommendedTime = new Date();
          updateOpenCourse(this.sequence.entity).then(response => {
            this.getData();
            this.tableData.map(item => {
              if (item.createTime) item.createTimeStr = new Date(item.createTime).toLocaleString().substring(0, 10).replace(/[\u4e00-\u9fa5]/g, '');
              if (item.recommendedTime) item.recommendedTimeStr = new Date(item.recommendedTime).toLocaleString().substring(0, 10).replace(/[\u4e00-\u9fa5]/g, '')
            })
          })
        } else {
          console.log('error submit!!');
          return false
        }
      })
    },
    cancelRecommend(scope) {
      this.$confirm(`确定取消推荐吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        scope.row.recommended = 0;
        scope.row.recommendedSeq = 100;
        scope.row.recommendedTime = '';
        updateOpenCourse(scope.row).then(res => {
          this.getData();
          this.$notify({
            title: '成功',
            message: '推荐已取消！',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '放弃取消推荐'
        })
      })
    },
    handleSizeChange(val) {
      console.log(val);
      this.currentpage = 1;
      this.pagesize = val.value;
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentpage = val.value;
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleFilter() {
      this.tableData = this.listFilter.filter(item => {
        if (this.listQuery.type[0] && item.categoryName !== this.listQuery.type[this.listQuery.type.length - 1]) return false;
        if (this.listQuery.property && item.type !== this.listQuery.property) return false;
        if (this.listQuery.keyword && item.title.toLowerCase().indexOf(this.listQuery.keyword.toLowerCase()) === -1) return false;
        if (this.listQuery.author && item.userName.toLowerCase().indexOf(this.listQuery.author.toLowerCase()) === -1) return false;
        return true
      });
      this.total = this.tableData.length
    },
    clearParams() {
      this.listQuery.type = [];
      this.listQuery.property = '';
      this.listQuery.keyword = '';
      this.listQuery.author = '';
      this.getData()
    },
    getData() {
      getRecommendOpenCourseList(getTenantId()).then(response => {
        response.data.items.map(item => {
          if (item.createTime) item.createTimeStr = new Date(item.createTime).toLocaleString().substring(0, 10).replace(/[\u4e00-\u9fa5]/g, '');
          if (item.recommendedTime) item.recommendedTimeStr = new Date(item.recommendedTime).toLocaleString().substring(0, 10).replace(/[\u4e00-\u9fa5]/g, '')
        });
        this.tableData = response.data.items;
        this.total = response.data.items.length;
        this.listFilter = response.data.items
      })
    },
    getCategoryList() {
      getCategoryList('course', getTenantId(),'0').then(response => {
        this.courseCategorys = response.data.items
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.allsearch {
  margin-top: 0px;
  padding: 0;
  .search-content {
    width: 100%;
  }
}
</style>
